<template>
  <base-layout simple>
    <article class="base-layout__inner column">
      <!-- 控制按钮 -->
      <t-space>
        <t-button @click="handleAdd">新建组织</t-button>
      </t-space>
      <!-- 查询条件 -->
      <t-form ref="form" :data="formData" :rules="rules" layout="inline">
        <t-form-item label="租户名称" name="name">
          <t-input
            v-model="formData.name"
            placeholder="请输入租户名称"
            clearable
            style="width: 200px"
          />
        </t-form-item>
        <t-form-item>
          <t-space>
            <t-button theme="primary" @click="handleSearch">查询</t-button>
            <t-button theme="default" @click="handleReset">重置</t-button>
          </t-space>
        </t-form-item>
      </t-form>

      <!-- 普通表格 -->
      <t-enhanced-table
        ref="table"
        row-key="id"
        :data="data"
        :columns="columns"
        :loading="loading"
        bordered
        size="small"
      />

      <!-- 新增/编辑组织抽屉 -->
      <t-drawer
        :visible="drawerVisible"
        @update:visible="drawerVisible = $event"
        size="500"
        placement="right"
      >
				<template #header>{{drawerTitle}}</template>
        <t-form
          ref="drawerForm"
          :data="drawerFormData"
          :rules="drawerRules"
          layout="vertical"
          label-align="top"
        >
          <t-form-item label="租户名称" name="name">
            <t-input
              v-model="drawerFormData.name"
              placeholder="请输入租户名称"
              clearable
            />
          </t-form-item>
          <t-form-item label="客服电话" name="servicePhone">
            <t-input
              v-model="drawerFormData.servicePhone"
              placeholder="请输入客服电话"
              clearable
            />
          </t-form-item>
          <t-form-item label="工作时间" name="workTime">
            <t-input
              v-model="drawerFormData.workTime"
              placeholder="请输入工作时间"
              clearable
            />
          </t-form-item>
          <t-form-item label="租户地址" name="address">
            <t-input
              v-model="drawerFormData.address"
              placeholder="请输入租户地址"
              clearable
            />
          </t-form-item>
        </t-form>

        <!-- 抽屉底部按钮 -->
        <template #footer>
          <t-space>
            <t-button theme="primary" @click="handleSubmit" :loading="submitLoading">保存</t-button>
            <t-button theme="default" @click="handleCancel">取消</t-button>
          </t-space>
        </template>
      </t-drawer>
    </article>
  </base-layout>
</template>

<script>
import BaseLayout from '@/components/base-layout/index.vue';
import {
  Button as TButton,
  Tag as TTag,
  EnhancedTable,
  Card as TCard,
  Form as TForm,
  FormItem as TFormItem,
  Input as TInput,
  Space as TSpace,
  Drawer as TDrawer,
  Radio as TRadio,
  RadioGroup as TRadioGroup,
  Popconfirm as TPopconfirm,
} from 'tdesign-vue';
import { getTenantList, addTenant, deleteTenant, updateTenant } from '@/api/tenant';

export default {
  name: 'SystemTempTenant',
  components: {
    BaseLayout,
    TButton,
    TTag,
    TEnhancedTable: EnhancedTable,
    TCard,
    TForm,
    TFormItem,
    TInput,
    TSpace,
    TDrawer,
    TRadio,
    TRadioGroup,
    TPopconfirm,
  },
  data() {
    return {
      loading: false,

      // 查询表单数据
      formData: {
        name: '',
      },

      // 表单验证规则
      rules: {},

      // 表格列配置
      columns: [
        {
          colKey: 'name',
          title: '租户名称',
          width: 250,
          ellipsis: true,
        },
        {
          colKey: 'servicePhone',
          title: '客服电话',
          width: 150,
        },
        {
          colKey: 'workTime',
          title: '工作时间',
          width: 200,
        },
        {
          colKey: 'address',
          title: '租户地址',
          width: 200,
          ellipsis: true,
        },
        {
          colKey: 'createdAt',
          title: '创建时间',
          width: 180,
        },
        {
          colKey: 'operate',
          title: '操作',
          width: 120,
          fixed: 'right',
          cell: (h, { row }) => {
            return h('div', { class: 'table-operations' }, [
              h(TButton, {
                props: {
                  variant: 'text',
                  theme: 'primary',
                  size: 'small',
                },
                on: {
                  click: () => this.handleEdit(row),
                },
              }, '编辑'),
              h(TPopconfirm, {
                props: {
                  content: '确认删除吗？',
                },
                on: {
                  confirm: () => this.handleDelete(row),
                },
              }, [
                h(TButton, {
                  props: {
                    variant: 'text',
                    theme: 'danger',
                    size: 'small',
                  },
                }, '删除'),
              ]),
            ]);
          },
        },
      ],

      // 组织列表数据
      data: [],

      // 抽屉相关
      drawerVisible: false,
      drawerTitle: '',
      submitLoading: false,
      drawerFormData: {
        name: '',
        servicePhone: '',
        workTime: '',
        address: '',
      },
      drawerRules: {
        name: [
          { required: true, message: '请输入租户名称' },
          { min: 1, max: 50, message: '租户名称长度必须在1-50之间' }
        ],
      },
    };
  },

  computed: {
    // 判断是否为编辑模式
    isEdit() {
      return !!this.drawerFormData.id;
    },
  },

  // 组件挂载时获取数据
  mounted() {
    this.fetchTenantList();
  },

  methods: {
    // 获取组织列表
    async fetchTenantList() {
      try {
        this.loading = true;
        const response = await getTenantList(this.formData);
        if (response.data.code === 200) {
          this.data = response.data.data || [];
        } else {
          console.error('获取组织列表失败:', response.data.message);
        }
      } catch (error) {
        console.error('获取组织列表出错:', error);
      } finally {
        this.loading = false;
      }
    },

    // 查询
    handleSearch() {
      console.log('查询条件:', this.formData);
      this.fetchTenantList();
    },

    // 重置
    handleReset() {
      this.formData = {
        name: '',
      };
      console.log('重置查询条件');
      this.fetchTenantList();
    },

    handleAdd() {
      console.log('打开新增抽屉');
      this.drawerTitle = '新建组织';
      this.resetForm();
      this.drawerVisible = true;
    },

    handleEdit(row) {
      console.log('打开编辑抽屉', row);
      this.drawerTitle = '编辑组织';
      this.drawerFormData = {
        id: row.id,
        name: row.name || '',
        servicePhone: row.servicePhone || '',
        workTime: row.workTime || '',
        address: row.address || '',
      };
      this.drawerVisible = true;
    },

    async handleDelete(row) {
      try {
        console.log('删除', row);
        const response = await deleteTenant(row.id);
        if (response.data.code === 200) {
          this.$message.success('删除组织成功');
          this.fetchTenantList();
        } else {
          this.$message.error(response.data.message || '删除组织失败');
        }
      } catch (error) {
        console.error('删除组织出错:', error);
        this.$message.error(error?.response?.data?.message || '删除组织失败');
      }
    },

    // 取消按钮处理
    handleCancel() {
      // 清除表单校验信息
      this.$refs.drawerForm.clearValidate();
      // 重置表单数据
      this.resetForm();
      // 关闭抽屉
      this.drawerVisible = false;
    },

    // 重置表单
    resetForm() {
      this.drawerFormData = {
        name: '',
        servicePhone: '',
        workTime: '',
        address: '',
      };
      this.$nextTick(() => {
        this.$refs.drawerForm?.clearValidate();
      });
    },

    // 抽屉提交
    async handleSubmit() {
      try {
        // 表单验证
        const valid = await this.$refs.drawerForm.validate();
        if (valid !== true) {
          return;
        }

        console.log('抽屉提交数据:', this.drawerFormData);

        // 根据是否为编辑模式调用不同接口
        if (this.isEdit) {
          await this.updateTenant();
        } else {
          await this.addTenant();
        }
      } catch (error) {
        console.error('表单验证失败:', error);
        this.$message.error('表单验证失败，请检查输入');
      }
    },

    // 新增租户
    async addTenant() {
      try {
        this.submitLoading = true;
        const response = await addTenant(this.drawerFormData);
        if (response.data.code === 200) {
          this.$message.success('新建组织成功');
          // 清除表单校验信息
          this.$refs.drawerForm.clearValidate();
          // 重置表单
          this.resetForm();
          this.drawerVisible = false;
          this.fetchTenantList();
        } else {
          this.$message.error(response.data.message || '新建组织失败');
        }
      } catch (error) {
        console.error('新建组织出错:', error);
        this.$message.error(error?.response?.data?.message || '新建组织失败');
      } finally {
        this.submitLoading = false;
      }
    },

    // 更新租户
    async updateTenant() {
      try {
        this.submitLoading = true;
        const response = await updateTenant(this.drawerFormData);
        if (response.data.code === 200) {
          this.$message.success('编辑组织成功');
          // 清除表单校验信息
          this.$refs.drawerForm.clearValidate();
          // 重置表单
          this.resetForm();
          this.drawerVisible = false;
          this.fetchTenantList();
        } else {
          this.$message.error(response.data.message || '编辑组织失败');
        }
      } catch (error) {
        console.error('编辑组织出错:', error);
        this.$message.error(error?.response?.data?.message || '编辑组织失败');
      } finally {
        this.submitLoading = false;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.search-card {
  margin-bottom: 16px;
}

:deep(.table-operations) {
  .t-button {
    margin-right: 8px;
  }
}

// 抽屉样式优化
:deep(.t-drawer__body) {
  padding: 20px;
}

:deep(.t-drawer__footer) {
  padding: 16px 20px;
  border-top: 1px solid #e7e7e7;
  background-color: #fafafa;
}

// 表单样式优化
:deep(.t-form) {
  .t-form-item {
    margin-bottom: 20px;
  }
}
</style>
